package com.lidx.back.statistics.dao.impl;

import com.lidx.back.statistics.commons.PageInfo;
import com.lidx.back.statistics.dao.IBugDao;
import com.lidx.back.statistics.entity.Bug;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by chen on 2017/2/18.
 */
@Repository
public class BugDaoImpl implements IBugDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void insertBug(Bug bug) {
        getSession().save(bug);
    }

    @Override
    public List<Bug> findBugs() {

        return getSession().createQuery("from Bug").list();
    }

    @Override
    public Bug getBugById(int id) {
        return (Bug) getSession().get(Bug.class,id);
    }

    @Override
    public boolean updateBug(Bug bug) {
        try{
            getSession().update(bug);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public PageInfo findBugsPage(int pageNo, int pageSize) {
        StringBuilder sb = new StringBuilder("from Bug");
        sb.append(" order by submitDate desc");
        Query query = getSession().createQuery(sb.toString());
        final int offset = PageInfo.countOffset(pageSize, pageNo);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List list = query.list();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNo(pageNo);
        pageInfo.setPageSize(pageSize);
        pageInfo.setList(list);
        long allRow = queryBugPageCount();
        pageInfo.setAllRow(allRow);
        pageInfo.setTotalPage(PageInfo.countTotalPage(pageSize, allRow));
        return pageInfo;
    }

    @Override
    public void deleteBug(Bug bug) {
        getSession().delete(bug);
    }

    private long queryBugPageCount() {
        Query query = getSession().createQuery("select count(1) from Bug");
        return  (Long) query.list().get(0);
    }
}
